﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Castle.Core.Configuration;
using Castle.Core.Configuration.Xml;
using System.Xml;
using System.IO;

namespace Inovout
{
    public class ApplicationWrapper
    {
        private string title;
        public string Title
        {
            get { return title; }
        }
        private IApplication application;
        public ApplicationWrapper(IApplication application)
        {
            ArgumentAssert.IsNotNull(application, "application");
            this.application = application;
        }
        public void Initialize()
        {
            InitializeFromConfig();
            ComponentRegistry.Initialize(application);
        }

        private IConfiguration applicationConfiguration;
        public IConfiguration ApplicationConfiguration
        {
            get { return applicationConfiguration; }
        }
        private void InitializeFromConfig()
        {
            XmlDocument xmlDocument = new XmlDocument();
            xmlDocument.Load(Path.Combine(application.Path, @"Configs\product.config"));
            IConfiguration productConfiguration = XmlConfigurationDeserializer.GetDeserializedNode(xmlDocument.DocumentElement);
            applicationConfiguration = productConfiguration.Children[0].Children.Single(c => c.Attributes["name"].Equals(application.Name));
            title = applicationConfiguration.Attributes["title"];

            IConfiguration dataSourceConfiguration = applicationConfiguration.Children.SingleOrDefault(c => c.Name.Equals("dataSource"));
            if (dataSourceConfiguration == null)
            {
                dataSourceConfiguration = new MutableConfiguration("dataSource");
                applicationConfiguration.Children.Add(dataSourceConfiguration);
            }
            IConfiguration databasesConfiguration = applicationConfiguration.Children.SingleOrDefault(c => c.Name.Equals("databases"));
            IConfiguration repositoriesConfiguration = applicationConfiguration.Children.SingleOrDefault(c => c.Name.Equals("repositories"));
            if (databasesConfiguration == null)
            {
                databasesConfiguration = new MutableConfiguration("databases");
                dataSourceConfiguration.Children.Add(databasesConfiguration);
                IConfiguration productDatabasesConfiguration = productConfiguration.Children.SingleOrDefault(c => c.Name.Equals("databases"));
                foreach (IConfiguration repositoryConfiguration in repositoriesConfiguration.Children)
                {
                    databasesConfiguration.Children.Add(productDatabasesConfiguration.Children.Single(c => c.Attributes["name"].Equals(repositoryConfiguration.Attributes["databaseName"])));
                }
            }
            dataSourceConfiguration.Children.Add(repositoriesConfiguration);
        }
    }
}
